#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@Time    : 2025/4/10 20:55
@Author  : zzj
@File    : app_handler.py
"""
import os

from flask import request
from openai import OpenAI

from internal.exception import FailException
from internal.schema.app_schema import CompletionReq
from pkg.response import success_json, validate_error_json


class AppHandler:
    """应用控制器"""

    def ping(self):
        raise FailException("数据未找到")
        # return {"ping": "pong"}

    def completion(self):
        """聊天接口"""
        # 1、提取从接口中获取的输入，POST请求
        req = CompletionReq()
        # 对请求参数进行验证
        if not req.validate():
            return validate_error_json(req.errors)
        query = request.json.get("query")
        # 2、构建OpenAI客户端，并发起请求
        # OpenAI 会默认读取 .env 文件中的 OPENAI_API_KEY 变量
        client = OpenAI(base_url=os.getenv("OPENAI_API_BASE"))
        # 3、得到请求响应，然后将OpenAI的响应传递给前端
        completion = client.chat.completions.create(
            model="glm-4",
            messages=[
                {"role": "system", "content": "你是智谱清言开发的聊天机器人，请根据用户的输入回复对应的信息"},
                {"role": "user", "content": query}
            ]
        )
        content = completion.choices[0].message.content
        # 4、把响应的文本返回给前端
        return success_json({"content": content})
